package fiuba.descuentos;

import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import Adapters.BenefitAdapter;
import Adapters.CategoryAdapter;
import Entities.Category;
import Entities.Benefit;
import Helpers.ContextHelper;
import Helpers.FileHelper;
import Listeners.CustomLocationListener;
import Service.IService;
import Service.Parameter;
import Service.RestServiceFactory;
import Service.WellKnownKeys;
import Service.WellKnownMethods;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BenefitDetail extends ActivityBase {
	private Benefit benefit;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.benefit);
        init();
    }
    
    private void init(){
    	Bundle extras = getIntent().getExtras(); 
    	if(extras !=null)
    	{
    		benefit = (Benefit)extras.get("benefit");
    	} 
    	
    	bindBenefit();
    }
    
    private void bindBenefit(){
    	if (benefit != null) {			
			
			TextView txtName = (TextView) this.findViewById(R.id.lbl_name);						
			bindLabelWithTitle(txtName,benefit.getName() + " (" + benefit.getCompany() + ")");
			
			TextView lblCategory = (TextView) this.findViewById(R.id.lbl_category);						
			bindLabelWithTitle(lblCategory,benefit.getCategory());
			
			TextView lblEndDate = (TextView) this.findViewById(R.id.lbl_end);
			Date date = new Date(benefit.getEndDateTime() * 1000);
			
			bindLabelWithTitle(lblEndDate,date.getDate() + "/" + (date.getMonth() + 1) + "/" + (date.getYear() + 1900));
			
			TextView txtAddress = (TextView) this.findViewById(R.id.lbl_address);
			String address = benefit.getFullAddress();
			String distance = benefit.getDistance();
			if(distance != null){
				address += " (" + distance + "km)";
			}					
			bindLabelWithTitle(txtAddress,address);
			
			TextView txtDescription = (TextView) this.findViewById(R.id.lbl_description);			
			bindLabelWithTitle(txtDescription,benefit.getDescription());
						

			ImageView logo = (ImageView) this.findViewById(R.id.image);
			logo.setTag(benefit);
			bindViewWithImage(logo ,benefit.getLogo(), "");
			
			ImageView map = (ImageView) this.findViewById(R.id.map);
			map.setTag(benefit);
			bindViewWithImage(map ,benefit.getMap(), FileHelper.getNameOfMapFromUrl(benefit.getMap()));
									
			if(ContextHelper.getUserId() > 0){
				Vector props = new Vector();
				Parameter userId = new Parameter(WellKnownKeys.UserIdKey,ContextHelper.getUserId());
				Parameter benefitId = new Parameter(WellKnownKeys.BenefitIdKey,benefit.getId());
				props.add(userId);
				props.add(benefitId);
				
				callService(WellKnownMethods.IsAlreadyLiked, props, false);
			}
			
			getLikes();
		}
				
    }
    
    private void getLikes(){
    	Vector props = new Vector();
		Parameter benefitId = new Parameter(WellKnownKeys.BenefitIdKey,benefit.getId());
		props.add(benefitId);
		callService(WellKnownMethods.GetLikes, props,false);
    }
    
    public void onServiceCompleted(JSONObject obj, String method) {
		if (WellKnownMethods.GetLikes.compareTo(method) == 0){
			onGetLikesCompleted(obj);
		}else if(WellKnownMethods.IsAlreadyLiked.compareTo(method) == 0){
			onIsAlreadyLikedCompleted(obj);
		}
	}

	private void onGetLikesCompleted(JSONObject obj) {
		boolean resultSuccess;
		hideLoading();
		try {
			resultSuccess = obj.getBoolean("success");
			if (resultSuccess) {
				String likes = obj.getString("response");
				TextView lblLikes = (TextView) this.findViewById(R.id.lbl_likes);						
				bindLabelWithTitle(lblLikes,"A " + likes + " usuarios le gusta esto");
			}else{
				showErrorMessage(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}				
	}
	
	private void onIsAlreadyLikedCompleted(JSONObject obj) {
		boolean resultSuccess;
		hideLoading();
		try {
			resultSuccess = obj.getBoolean("success");
			if (resultSuccess) {
				boolean alreadyLiked = obj.getBoolean("response");
				ImageView likeIt = (ImageView) this.findViewById(R.id.likeit);
				if(!alreadyLiked){
					likeIt.setVisibility(View.VISIBLE);
					
					likeIt.setOnClickListener(new View.OnClickListener() {
			            public void onClick(View v) {
			            	Vector props = new Vector();
			            	Parameter userId = new Parameter(WellKnownKeys.UserIdKey,ContextHelper.getUserId());
							Parameter benefitId = new Parameter(WellKnownKeys.BenefitIdKey,benefit.getId());
							props.add(userId);
							props.add(benefitId);
							
							callService(WellKnownMethods.LikeBenefit, props);
							v.setVisibility(View.INVISIBLE);
							getLikes();
			            }
			        });
					
				}else{
					likeIt.setVisibility(View.INVISIBLE);
				}
			}else{
				showErrorMessage(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}				
	}
    
    private void bindLabelWithTitle(TextView label, String name) {
		label.setText(name);
	}

	private void bindViewWithImage(ImageView imageButton, String logo, String mapName) {
		try {
			Bitmap bmp = FileHelper.getImageBitMap(logo,mapName);
			imageButton.setImageBitmap(bmp);
		} catch (Exception e) {

		}
	}
       
}